<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品添加</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row :gutter="0">
          <!-- 提示信息 -->
          <el-col>
            <el-alert title="提示：想要提示的信息" type="warning" :show-icon="true"></el-alert>
          </el-col>
        </el-row>
      </div>

      <!-- 含状态步骤条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" simple>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- Tabs 标签页 -->
      <el-form :model="addFormData" :rules="addFormRules" ref="addFormRef" label-position="top">
        <el-tabs
          v-model="activeIndex"
          :tab-position="tabPosition"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="addFormData.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="addFormData.price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="number">
              <el-input v-model="addFormData.number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="weight">
              <el-input v-model="addFormData.weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="type">
              <el-cascader
                expand-trigger="hover"
                :options="productsTypeList"
                :props="cascaderProps"
                v-model="addFormData.type"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.name" v-for="item in dynamicParamsData" :key="item.id">
              <el-checkbox-group v-model="item.values">
                <el-checkbox
                  :label="value"
                  v-for="(value,i) in item.values"
                  :key="i"
                  :border="true"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.name" v-for="item in staticParamsData" :key="item.id">
              <el-input v-model="item.values"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action	必选参数，上传的地址 -->
            <el-upload
              ref="uploadFormRef"
              :action="this.uploadUrl"
              list-type="picture-card"
              name="file"
              :limit="9"
              :data="dataOss"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <el-dialog :visible.sync="imgDialogVisible">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addFormData.content" :options="editorOption" />
            <el-button style="margin-top:15px" type="primary" @click="addFormOp">发布</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>


<script>
import _ from 'lodash'

export default {
  data() {
    return {
      activeIndex: '0',
      tabPosition: 'left',
      productsTypeList: [],
      addFormData: {
        name: '',
        price: 0,
        number: 0,
        weight: 0,
        // 商品所属的分类数组
        type: [],
        // 商品的图片
        images: [],
        // 商品的内容
        content: '',
        attrs: [],
      },
      addFormRules: {
        name: [{ required: true, message: '请输入商品名', trigger: 'blur' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        type: [{ required: true, message: '请输入商品类型', trigger: 'blur' }],
      },
      // 级联选择器的绑定配置对象
      cascaderProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        // checkStrictly: true
      },
      dynamicParamsData: [],
      staticParamsData: [],
      // upload 组件 data
      imgDialogVisible: false,
      dialogImageUrl: '',
      disabled: false,
      dataOss: {},
      // 富文本组件
      editorOption: {
        placeholder: '请输入内容',
      },
    }
  },
  created() {
    this.getProductsTypeList()
  },
  methods: {
    // 获取商品分页
    async getProductsTypeList() {
      await this.$http
        .get('/productsType')
        .then((res) => {
          res = res.data
          if (!res.code || res.code == 0)
            return this.$message.error(
              res.msg || window.defineGlobalConstData.getError
            )

          this.productsTypeList = res.data.list
          this.deleteEmptyChildren(this.productsTypeList)
        })
        .catch((err) => {
          return this.$message.error(
            err.message || window.defineGlobalConstData.getError
          )
        })
    },
    // 删除为空的子节点
    deleteEmptyChildren(obj) {
      // console.log(obj)
      function traversal(data) {
        for (var item of data) {
          if (item.children) {
            if (item.children.length > 0) {
              traversal(item.children)
            }
            if (item.children.length === 0) {
              delete item.children
            }
          }
        }
      }

      traversal(obj)
    },
    // 级联选择器选中项变化，触发
    handleChange() {
      if (this.addFormData.type.length !== 3) {
        this.addFormData.type = []
      }
    },
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addFormData.type.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    async tabClicked() {
      if (this.activeIndex === '1') {
        // 动态参数
        await this.$http
          .get(`/productsType/${this.selectedThreeLevelId}/attributes`, {
            params: { selectedtype: 1 },
          })
          .then((res) => {
            res = res.data
            // console.log(res)
            if (res.code !== 1)
              return this.$message.error(
                res.msg || window.defineGlobalConstData.getError
              )

            res.data.forEach((item) => {
              item.values = item.values ? item.values.split(',') : []
            })
            this.dynamicParamsData = res.data
          })
          .catch((err) => {
            this.$message.info(
              err.message || window.defineGlobalConstData.getError
            )
          })
      } else if (this.activeIndex === '2') {
        // 静态属性
        await this.$http
          .get(`/productsType/${this.selectedThreeLevelId}/attributes`, {
            params: { selectedtype: 2 },
          })
          .then((res) => {
            res = res.data
            // console.log(res)
            if (res.code !== 1)
              return this.$message.error(
                res.msg || window.defineGlobalConstData.getError
              )
            // console.log(res.data)
            this.staticParamsData = res.data
          })
          .catch((err) => {
            this.$message.info(
              err.message || window.defineGlobalConstData.getError
            )
          })
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.imgDialogVisible = true
    },
    async beforeUpload(file) {
      // console.log(file)
      const { data: sign } = await this.$http.get(this.uploadGetSignUrl)
      const fileName = file.uid + '_' + file.lastModified
      this.dataOss = {
        key: 'uploads/img/' + fileName + this.getSuffix(file.name), // file.name.split('.')[-1],
        // expire: sign.data.expire,
        ossAccessKeyId: sign.ossKeyId,
        policy: sign.policy,
        signature: sign.sign,
        success_action_status: 200,
      }
    },
    handleRemove(file) {
      // 拼装要删除的图片路径
      const fileName = file.raw.uid + '_' + file.raw.lastModified
      const imgUrl = 'uploads/img/' + fileName + this.getSuffix(file.name)
      // uploadFiles 和 images 中 找到该图片对应的索引值
      const i = this.addFormData.images.findIndex((x) => x === imgUrl)
      // 调用数组的 splice 方法，进行删除
      this.addFormData.images.splice(i, 1)

      // uploadFiles 中 找到该图片对应的索引值
      const j = this.$refs.uploadFormRef.uploadFiles.findIndex((x) => {
        // console.log(x)
        return x.raw.uid + '_' + x.raw.lastModified === fileName
      })
      // 调用数组的 splice 方法，进行删除
      this.$refs.uploadFormRef.uploadFiles.splice(j, 1)
    },
    handleUploadSuccess(response, file, fileList) {
      // 将地址放入表单数组中
      const fileName = file.raw.uid + '_' + file.raw.lastModified
      this.addFormData.images.push(
        'uploads/img/' + fileName + this.getSuffix(file.name)
      )
      // console.log(fileList)
    },
    handleUploadError(err, file, fileList) {
      this.$message.error(window.defineGlobalConstData.upSuccess)
    },
    // 添加操作
    addFormOp() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) {
          return this.$message.error('缺少必要的表单信息')
        }
        // 验证通过，执行添加操作业务逻辑
        const formData = _.cloneDeep(this.addFormData)
        formData.type = formData.type.join(',')
        this.dynamicParamsData.forEach((item) => {
          const info = { attr_id: item.id, attr_values: item.values.join(',') }
          formData.attrs.push(info)
        })
        this.staticParamsData.forEach((item) => {
          const info = { attr_id: item.id, attr_values: item.values }
          formData.attrs.push(info)
        })
        // console.log(formData)
        // 发起添加请求
        this.$http
          .post('/products', formData)
          .then((res) => {
            res = res.data
            if (res.code !== 1)
              return this.$message.error(
                res.msg || window.defineGlobalConstData.opError
              )

            this.$message.success(
                res.msg || window.defineGlobalConstData.opSuccess
              )
            this.$router.push('/products')
          })
          .catch((err) => {
            console.log(err)
            this.$message.error(
              err.message || window.defineGlobalConstData.opError
            )
          })
      })
    },
  },
  computed: {
    selectedThreeLevelId() {
      if (this.addFormData.type.length === 3) {
        return this.addFormData.type[2]
      }
      return null
    },
  },
}
</script>

<style lang="scss" scoped>
.el-steps {
  margin-bottom: 15px;
}

.el-checkbox {
  margin: 0 10px 0 0 !important;
}
</style>